package com.wondream.example.io.nio.file.simple;

import org.apache.commons.io.IOUtils;

import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * @author wangjun
 * @note NioWriteTest
 * @date 2023-11-24  11:44
 */
public class NioWriteTest {
    public static void main(String[] args) throws Exception {
        // 1.创建输出流
        FileOutputStream fos = new FileOutputStream("logs/basic.txt");
        // 2.从流中得到一个通道
        FileChannel fileChannel = fos.getChannel();
        // 3.分配缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        // 4.往缓冲区填充数据
        String var1 = "hello, nio";
        byteBuffer.put(var1.getBytes(StandardCharsets.UTF_8));
        // 5.翻转缓冲区
        byteBuffer.flip();
        // 6.将缓冲区写入通道
        fileChannel.write(byteBuffer);
        // 7.关闭io
        IOUtils.closeQuietly(fos);
    }
}
